package org.aceor.mddal.config.datasource;

import com.google.common.base.Objects;
import com.google.common.base.Strings;

/**
 * Created by lxue on 16/3/27.
 */
public class Weight {
    /**
     * 读权重.优先级相同时,按权重比例选取
     */
    public int r;

    /**
     * 写权重
     */
    public int w;

    /**
     * 读优先级
     */
    public int p;

    /**
     * 写优先级
     */
    public int q;

    public Weight(String weightStr) {
        if (Strings.isNullOrEmpty(weightStr)) {
            throw new NullPointerException();
        }
        initValue();
        parseWeight(weightStr);
    }

    private void initValue() {
        r = w = p = q = 0;
    }

    /**
     * 解析 r:10,w:10,p:0,q:0
     *
     * @param weightStr
     */
    private void parseWeight(String weightStr) {
        String[] weightEles = weightStr.split(",");
        for (String weightEle : weightEles) {
            parseWeightEle(weightEle);
        }
    }

    /**
     * 解析r:10
     *
     * @param weightEle
     */
    private void parseWeightEle(String weightEle) {
        if (Strings.isNullOrEmpty(weightEle)
                || !weightEle.contains(":")) {
            throw new IllegalArgumentException();
        }
        String[] pair = weightEle.split(":");
        if (null == pair
                || pair.length != 2
                || Strings.isNullOrEmpty(pair[0])
                || Strings.isNullOrEmpty(pair[1])) {
            throw new IllegalArgumentException();
        }
        if (Objects.equal("R", pair[0].toUpperCase())) {
            r = Integer.valueOf(pair[1]);
        } else if (Objects.equal("W", pair[0].toUpperCase())) {
            w = Integer.valueOf(pair[1]);
        } else if (Objects.equal("P", pair[0].toUpperCase())) {
            p = Integer.valueOf(pair[1]);
        } else if (Objects.equal("Q", pair[0].toUpperCase())) {
            q = Integer.valueOf(pair[1]);
        } else {
            throw new IllegalArgumentException();
        }
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("r", r)
                .add("w", w)
                .add("p", p)
                .add("q", q)
                .toString();
    }
}
